package com.netease.yunxin.kit.conversationkit.ui.page

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.drake.brv.utils.addModels
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.common.Constants
import com.luoxiang.lib_common.utils.AESUtil
import com.luoxiang.lib_common.utils.MmkvUtil
import com.luoxiang.lib_common.utils.NetUtils
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.yunxin.kit.common.ui.fragments.BaseFragment
import com.netease.yunxin.kit.conversationkit.ui.R
import com.netease.yunxin.kit.conversationkit.ui.databinding.FragmentConversationFriendsBinding
import com.netease.yunxin.kit.conversationkit.ui.model.VideoCallListBean
import com.netease.yunxin.kit.conversationkit.ui.model.VideoCallListBeanList
import com.netease.yunxin.kit.conversationkit.ui.utils.TimeUtils
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant
import com.netease.yunxin.kit.corekit.route.XKitRouter
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * Author: Sakura

 * Date: 2023/4/21

 * Description:
 */
class ConversationFriendsFragment : BaseFragment() {

    private lateinit var binding: FragmentConversationFriendsBinding

    private var mIsLoaded = false

    private var mIsLoad: Boolean = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentConversationFriendsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.refresh.setOnLoadMoreListener {
            mIsLoad = true
            initData()
        }
        binding.refresh.setOnRefreshListener {
            initData()
        }
        initRecyclerView()
    }

    override fun onResume() {
        super.onResume()
        if (!mIsLoaded && !isHidden) {
            initData()
        }
    }

    private fun initRecyclerView() {
        binding.recycler.setHasFixedSize(true)
        binding.recycler.linear().setup {
            addType<VideoCallListBeanList>(R.layout.item_conversation_friends)
            onBind {
                (getModel(modelPosition) as VideoCallListBeanList).let {
                    Glide.with(requireActivity())
                        .load("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + it.icon)
                        .transform(CenterCrop(), CircleCrop())
                        .into(findView(R.id.imageCover))
                    findView<TextView>(R.id.testState).text = it.name
                    if (it.online == 1) {
                        findView<ImageView>(R.id.imageOnline).visibility = View.VISIBLE
                    } else {
                        findView<ImageView>(R.id.imageOnline).visibility = View.GONE
                    }
                    it.userId?.let { id ->
                        NIMClient.getService(MsgService::class.java)
                            .queryRecentContact(id, SessionTypeEnum.P2P)
                            .let { info ->
                                if (info != null && info.content?.isNotEmpty() == true){
                                    findView<TextView>(R.id.textContent).text = info.content
                                    findView<TextView>(R.id.textTime).text = TimeUtils.timestampToDate(info.time)
                                }
                            }
                    }
                }
            }
            onClick(R.id.imageCover) {
                (getModel(modelPosition) as VideoCallListBeanList).let {
                    LiveEventBus.get<String>("startDetailsActivity").post(it.userId)
                }
            }
            onClick(R.id.roots) {
                (getModel(modelPosition) as VideoCallListBeanList).let {
                    XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(
                        RouterConstant.CHAT_KRY,
                        UserInfo(it.userId!!, it.name!!, it.icon!!)
                    ).withContext(context).navigate()
                }
            }
        }
    }

    private fun initData() {
        mIsLoaded = true
        NetUtils.getInstance().apiService.getMutualFriendList(
            Constants.MmkvConst.EXTRA,
            MmkvUtil.decodeString(Constants.MmkvConst.TOKEN),
        ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onError(e: Throwable?) {
                    Toast.makeText(requireContext(), e?.message, Toast.LENGTH_SHORT).show()
                }

                override fun onComplete() {}

                override fun onNext(value: NumberBean?) {
                    binding.refresh.finishRefresh()
                    value?.data?.let {
                        val json = AESUtil.aesDecryptString(it, Constants.MmkvConst.KEY)
                        val bean = Gson().fromJson(json, VideoCallListBean::class.java)
                        if (bean?.data?.hosts?.isNotEmpty() == true) {
                            if (mIsLoad) {
                                binding.recycler.addModels(bean.data.hosts)
                                return@let
                            }
                            binding.recycler.models = bean.data.hosts
                        } else {
                            binding.refresh.finishLoadMoreWithNoMoreData()
                            binding.recycler.models = listOf()
                        }
                    }
                }
            })
    }
}